<?php

namespace app\admin\controller;

use think\Controller;
use think\captcha\Captcha;
use app\common\model\AdminUser;
use think\Request;
use app\common\validate\AdminLogin;
use app\common\lib\Util;

class Login extends Controller
{
    //后台登录
    public function login(Request $request)
    {
        $token = $request->token('__token__', 'sha1');
        $this->assign('token', $token);
        return $this->fetch();
    }

    public function doLogin(AdminUser $adminUser, Request $request, AdminLogin $tokenValidate)
    {
        $data = [
            'username' => $request->username,
            'password' => $request->password,
            '__token__' => $request->__token__
        ];
        /*
         token 有效防止重复提交，以及跨站伪造请求
         token验证实际是比较session中的token和请求的参数token是否一致,验证完后__token__值被设置为null
        */
        if (!$tokenValidate->check($data)) {
            $newToken = $request->token('__token__', 'sha1');
            return Util::apiResponse(['__token__' => $newToken], $tokenValidate->getError(), -1);
        }
        $newToken = $request->token('__token__', 'sha1');
        $verify = $request->verify;
        //验证码验证
        if (!captcha_check($verify)) {
            return Util::apiResponse(['__token__' => $newToken], "验证码错误！", -1);
        }
        $result = $adminUser->login($data['username'], $data['password']);
        if ($result) {
            $adminUser->save(['login_time' => time()], ['username' => $data['username']]);
            return Util::apiResponse(['__token__' => $newToken], "登录成功！", 1);
        }
        return Util::apiResponse(['__token__' => $newToken], $adminUser->err_msg, -1);
    }

    //验证码
    public function verify()
    {
        $config = [
            'length' => 4,

            'expire' => 300,

            'useNoise' => true,

            'useCurve' => true,

            'useImgBg' => false,
        ];
        $captcha = new Captcha($config);
        return $captcha->entry();
    }


    //退出登录
    public function logout()
    {
        session("user_session", NULL);
        $this->redirect(url('admin.login'));
    }
}